import sys
import xbmc, xbmcgui, xbmcplugin,xbmcaddon

import urllib
import urllib2
import cookielib
import logging
import simplejson

# from subsonic import SubsonicJson
from subsonic.SubsonicJson import SubsonicJson

#plugin constants
__plugin__ = "Subsonic"
__author__ = "alexj"
__url__ = "http://www.backpocket.com"
__svn_url__ = "http://www.backpocket.com"
__version__ = "0.156"

print "[PLUGIN] '%s: version %s' initialized!" % (__plugin__, __version__)

settings = xbmcaddon.Addon(id='plugin.subsonic')

# http://wiki.xbmc.org/index.php?title=HOW-TO_debug_Python_Scripts_with_Eclipse
# plugin modes
handle = int(sys.argv[1])

username = settings.getSetting("username")
password = settings.getSetting("password")
subsonic_host = settings.getSetting("subsonic_host")

print "[PLUGIN] '%s / %s: %s' initialized!" % (username, password, subsonic_host)


sub = SubsonicJson(subsonic_host,username,password)
# parameter keys
PARAMETER_KEY_MODE = "mode"


# plugin handle


# utility functions
def parameters_string_to_dict(parameters):
    ''' Convert parameters encoded in a URL to a dict. '''
    paramDict = {}
    if parameters:
        paramPairs = parameters[1:].split("&")
        for paramsPair in paramPairs:
            paramSplits = paramsPair.split('=')
            if (len(paramSplits)) == 2:
                paramDict[paramSplits[0]] = paramSplits[1]
    return paramDict

def addDirectoryItem(name, isFolder=True, parameters={}):
    ''' Add a list item to the XBMC UI.'''
    li = xbmcgui.ListItem(name)
    url = sys.argv[0] + '?' + urllib.urlencode(parameters)
    #print "addDirectoryItem handle = [%s] %s   url = %s" % (int(sys.argv[1]), name, url)    
    return xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=li, isFolder=isFolder)


# UI builder functions
def showMainMusicFolders():
    ''' Show the plugin root menu. '''
    # {u'musicFolders': {u'musicFolder': [{u'id': 0, u'name': u'Music'}, {u'id': 1, u'name': u'Videos'}]}, u'status': u'ok', u'version': u'1.5.0', u'xmlns': u'http://subsonic.org/restapi'}
    resp = sub.getMusicFolders()
    folders = resp['musicFolders']['musicFolder']    
    #print resp
    #print "val: %s" % folders
    
    # {u'id': 1, u'name': u'Videos'}
    for folder in folders:        
        addDirectoryItem(name=folder['name'], parameters={ 'action': 'viewMusicFolderContent' , 'musicFolder': folder['id'] }, isFolder=True)
        

    addDirectoryItem(name='Config Setting', parameters={ 'action': 'viewConfig'}, isFolder=False)
    xbmcplugin.endOfDirectory(handle=handle, succeeded=True)
    
def viewMusicFolderContent(params):
    print "viewMusicFolderContent %s" % params
    musicFolder = int(params.get('musicFolder', "0"))
    
    contents = sub.getIndexes(musicFolder)
    if contents['status'] == 'ok':
        #print 'got indexes'
        indexes = contents['indexes']['index']
        #print "indexes: %s" % indexes
        # ['artist']
        for index in indexes:
            #print "subdirs: %s" % index
            #print "subdirs-name: %s" % index['name']
            #print "subdirs-artist: %s" % index['artist']
            
            folders = index['artist']
            #print "folders-type: %s" % type(folders)
            if type(folders).__name__=='list':
                # use as a container                
                for folder in folders:                
                    addDirectoryItem(folder['name'], parameters={ 'action':'viewFolderContents', 'folderId': folder['id'] }, isFolder=True)
            else:
                # not a container!
                addDirectoryItem(folders['name'], parameters={ 'action':'viewFolderContents', 'folderId': folders['id'] }, isFolder=True)

        
    xbmcplugin.endOfDirectory(handle=handle, succeeded=True)

def addToFolder(file):
    isDir = file['isDir']
    #print "folders-type: %s" % type(folders)
    if isDir ==False:
        print "addToFolder file: %s" % file
        isVideo = file['isVideo']
        name = file['title']
        parameters={ 'action':'streamContent', 'id': file['id'] }
                        
        li = xbmcgui.ListItem(name)
        url = sys.argv[0] + '?' + urllib.urlencode(parameters)
        xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=li, isFolder=False)
    else:
        print "addToFolder dir: %s" % file
        name = file['title']    
        parameters={ 'action':'viewFolderContents', 'folderId': file['id'] }
                        
        li = xbmcgui.ListItem(name)
        url = sys.argv[0] + '?' + urllib.urlencode(parameters)
        xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=li, isFolder=True)    

def viewFolderContents(params):
    print "viewFolderContents %s" % params
    folderId = params.get('folderId', "0")
    
    contents = sub.getMusicDirectory(folderId)
    print contents
    if contents['status'] == 'ok':
        #print 'got indexes'
        files = contents['directory']['child']
        if type(files).__name__=='list':
            for file in files:
                addToFolder(file)
        else:
            addToFolder(files)
            
    xbmcplugin.endOfDirectory(handle=handle, succeeded=True)


def streamContent(params):
    print "streamContent %s" % params
    id = params.get('id', "0")
    
    if bool(settings.getSetting("transcode")):
        maxBitRate = int(settings.getSetting("transcode_bitrate"))
        url = sub.createStreamUrl(id, maxBitRate)
        print "Transcoding to a max bitrate of %s" %maxBitRate
    else:
        url = sub.createDownloadUrl(id)
        print "Using download URL - Not Transcoding"
    #xbmc.Player(xbmc.PLAYER_CORE_AUTO).play(str() )
    print 'Playing URL: %s' % url
    xbmc.Player(xbmc.PLAYER_CORE_AUTO).play(str(url) )
    xbmc.sleep(200)



# parameter values
params = parameters_string_to_dict(sys.argv[2])
action = params.get('action', "showMainMusicFolders")

mode = int(params.get(PARAMETER_KEY_MODE, "0"))
print "##########################################################"
print("params: %s" % params)
print("action: %s" % action)
print "##########################################################"


i=0
for arg in sys.argv:
    print "sys.argv[%s] = %s" % (i, arg)
    i=i+1

# Depending on the mode, call the appropriate function to build the UI.




if sub.ready == True:
    if action == 'viewFolderContents':
        print 'viewFolderContents %s' % params
        viewFolderContents(params)# new start
    elif action == 'viewMusicFolderContent':
        print 'viewMusicFolderContent %s' % params
        viewMusicFolderContent(params)# new start
    elif action == 'streamContent':
        print 'streamContent %s' % params
        streamContent(params)# new start
    
    elif action == 'viewConfig':
        settings.openSettings()      # this will open settings window
    else:
        ok = showMainMusicFolders()
else:
    print 'Not Ready'
    dlg = xbmcgui.Dialog()
    dlg.ok('Error', 'Unable to communicate with Subsonic Server\nPlease check subsonic configuration')
    del dlg
    settings.openSettings()      # this will open settings window

    
    
